/*
 *     AD 界面
 */

using System;
using System.Collections;
using System.Globalization;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;

namespace Dolls
{
	/// <summary>
	/// 广告界面
	/// </summary>
	public class uiAD : uiMonoBase
	{
		[Tooltip("数据编号")]
		public long dataIndex;

		[Tooltip("主要文本显示组件")]
		public CharsForeach mainTextComponent;

		[Tooltip("倒计时组件")]
		public UiLongTimer countdownComponent;

		[Tooltip("倒计时结束时间字符串【yyyy-M-d H:m:s")]
		public string endTime;

		public GameObject reward1Component1;
		public GameObject reward1Component2;
		public GameObject reward1Component3;
		public Button     rewardGettingButton;

		private UiAdDataManager DataManager { get; set; } = UiAdDataManager.Inst;
		private UiAdData        Data        { get; set; }
		private int             RewardCount { get; set; }
		private bool            TimesUp     { get; set; }

		public event Action<uiAD, int> RewardGotEventHandle;

		private void Start()
		{
			DataManager.Init();
			Btn_Open();
		}

		public override void Btn_Open()
		{
			base.Btn_Open();
			dataIndex = DataManager.NextRandomIndex();
			Data      = DataManager.FindItem(dataIndex);
			Assert.IsNotNull(Data);
			var targetTime = DateTime.ParseExact(endTime, "yyyy-M-d H:m:s", CultureInfo.InvariantCulture);
			TimesUp     = false;
			RewardCount = 0;

			reward1Component1.gameObject.SetActive(false);
			reward1Component2.gameObject.SetActive(false);
			reward1Component3.gameObject.SetActive(false);
			rewardGettingButton.gameObject.SetActive(false);

			mainTextComponent.FinishedEventHandle  += _ => { StartCoroutine(ShowReward()); };
			countdownComponent.FinishedEventHandle += _ => { TimesUp = true; };
			//从数据中读取需要显示的内容
			mainTextComponent.DisplayIndividually(Data.Description);
			//直接写死需要显示的内容用于测试。
			// mainTextComponent.DisplayIndividually(
			// 	"《<color=#ff0000ff><b>星爆-图斯坦陨落星球</b></color>》起源于2008年的独立游戏《<color=#008000ff><i>末日猎手</i></color>》设定。讲述的是一个末日世界里AI，人类，进化变异的地球圈生物与入侵的外星智慧之间的战争。");
			countdownComponent.StartCountdown(targetTime);
		}

		public override void Btn_Close()
		{
			base.Btn_Close();
			gameUtility.Log($"已执行关闭{gameObject.activeInHierarchy}");
		}

		public void Btn_Get()
		{
			switch (RewardCount)
			{
				case 0:
					reward1Component1.gameObject.SetActive(false);
					reward1Component2.gameObject.SetActive(false);
					reward1Component3.gameObject.SetActive(true);
					RewardCount++;
					RewardGotEventHandle?.Invoke(this, 0);
					break;
				case 1:
					RewardGotEventHandle?.Invoke(this, 1);
					Btn_Close();
					break;
			}
		}

		private IEnumerator ShowReward()
		{
			while (true)
			{
				if (TimesUp)
					break;
				yield return new WaitForSeconds(1);
			}
			reward1Component1.gameObject.SetActive(true);
			reward1Component2.gameObject.SetActive(true);
			rewardGettingButton.gameObject.SetActive(true);
		}
	}
}